var express = require('express');
var crypto = require('crypto');
var router = express.Router();
//var User = require('../models/user.js');
var usr=require('../dao/userDao');
var weibo= require('../dao/weiboDao');

var md5 = crypto.createHash('md5');

/* GET home page. */
router.get('/', function(req, res, next) {
   var user=req.session.isuser;
   res.locals.user=user;
    weibo.getWeiboList(function (result) {
      res.render('index', { title: '首页',posts:result});
    })
});


router.get('/hello', function(req, res, next) {
  res.send('The time is ' + new Date().toString());
});


router.get('/u/:user', function(req, res) {
  var user=req.session.isuser;
  res.locals.user=user;
  usr.getUser(req.params.user,function(user) {
    if(user===undefined){
      return res.redirect('/');
    }
    weibo.getWeibo(user.id,function (result) {
      res.render('user', { title: '个人首页',posts:result});

    });
  });


});

router.post('/post', function(req, res) {
  var user=req.session.isuser;
  weibo.Insweibo(user.id,req.body.content,function (err) {
    if(err) throw err;
    var data={
      flag:'true',
      name:user.name
    }
    res.send(data);
  })


});

router.get('/reg', function(req, res) {
  res.render('reg', { title: '用户注册' });
});


router.post('/reg', function(req, res) {
  /*md5加密*/
  var password  = crypto.createHash('md5').update(req.body.password).digest('base64');
  usr.Insuser(req.body.name ,password,function (err) {
      if(err) throw err;
      res.send('true');

  });
});




router.get('/login', function(req, res) {
  res.render('login', { title: '用户登录' });
});

router.post('/login', function(req, res) {
  var isuser;
  var password  = crypto.createHash('md5').update(req.body.password).digest('base64');
  usr.login(req.body.name,password,function (user) {
    if(user===undefined){
      res.send('false');
    }else{
      isuser=user;
      req.session.isuser = isuser;
      res.send('true');

    }
  });

});

router.get('/logout', function(req, res) {
  req.session.isuser = isuser;
});

//用户名验证是否存在
router.post('/checkuser', function(req, res) {
  usr.checkuser(req.body.name, function (result) {
    if(result===undefined){
      res.send('true');
    }else if(result.length>0){
      res.send('false');
    }else{
      res.send('true');
    }
  });
});









module.exports = router;
